package com.hmall.controller;

import com.github.pagehelper.PageInfo;
import com.hdmall.business.common.annotation.LoginRequired;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hmall.mapper.SysUserMapper;
import com.hmall.model.MallShipping;
import com.hmall.model.SysUser;
import com.hmall.service.ShippingService;
import com.hmall.util.TokenUtil;
import com.mysql.fabric.Server;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@RestController
@RequestMapping("shipping/")
@CrossOrigin(origins = "http://localhost:8088", maxAge = 3600)
@Api(value = "发货操作API", description = "发货操作类API说明")
public class ShippingController {


    @Autowired
    private ShippingService iShippingService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    JedisPool jedisPool;

    TokenUtil tokenUtil = new TokenUtil();

    @PostMapping("findprovince")
    @ApiOperation(value = "查询省份")
    public ServerResponse findprovince(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "100") int pageSize) throws Exception {

        return iShippingService.findprovince(pageNum, pageSize);
    }

    @PostMapping("finddetail")
    @ApiOperation(value = "查询下一级")
    public ServerResponse finddetail(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "100") int pageSize, Integer id) throws Exception {

        return iShippingService.finddetail(pageNum, pageSize, id);
    }


    //PC前端
    @PostMapping("findShip")
    @ApiOperation(value = "根据收货地址id得到收货地址")
    public ServerResponse<MallShipping> findShip(Integer shippingId) {

        return iShippingService.findShip(shippingId);
    }

    @LoginRequired
    @PostMapping("add")
    @ApiOperation(value = "增加发货")
    public ServerResponse add(String token, Integer userId, MallShipping shipping) throws Exception {

        ServerResponse response = getUserId(token, userId);
        if (response.getStatus() == 0) {
            userId = (Integer) response.getData();
        }else{
            return ServerResponse.createByErrorMessage("请输入正确的用户id");
        }
        if (shipping.getDefaultCheck() == null) {
            shipping.setDefaultCheck(0);
        }

        //如果该地址为默认地址，则将其他的默认地址去掉
        if (shipping.getDefaultCheck() == 1) {
            List<MallShipping> shipList = iShippingService.list(userId).getData();
            if (shipList != null && shipList.size() > 0) {
                for (MallShipping ship : shipList) {

                    if (ship.getId() == shipping.getId()) {
                        continue;
                    }
                    if (ship.getDefaultCheck() == 1) {
                        ship.setDefaultCheck(0);
                        iShippingService.update(userId, ship);
                    }
                }
            }
        }
        return iShippingService.add(userId, shipping);
    }


    @LoginRequired
    @PostMapping("del")
    @ApiOperation(value = "删除发货")
    public ServerResponse del(String token, Integer userId, Integer shippingId) throws Exception {

        ServerResponse response = getUserId(token, userId);
        if (response.getStatus() == 0) {
            userId = (Integer) response.getData();
        }else{
            return ServerResponse.createByErrorMessage("请输入正确的用户id");
        }

        return iShippingService.del(userId, shippingId);
    }

    @LoginRequired
    @PostMapping("update")
    @ApiOperation(value = "更新发货")
    public ServerResponse update(String token, Integer userId, MallShipping shipping) throws Exception {

        ServerResponse response = getUserId(token, userId);
        if (response.getStatus() == 0) {
            userId = (Integer) response.getData();
        }else{
            return ServerResponse.createByErrorMessage("请输入正确的用户id");
        }
        return iShippingService.update(userId, shipping);
    }


    @LoginRequired
    @PostMapping("select")
    @ApiOperation(value = "发货选择")
    public ServerResponse<MallShipping> select(String token, Integer userId, Integer shippingId) throws Exception {

        ServerResponse response = getUserId(token, userId);
        if (response.getStatus() == 0) {
            userId = (Integer) response.getData();
        }else{
            return ServerResponse.createByErrorMessage("请输入正确的用户id");
        }
        return iShippingService.select(userId, shippingId);
    }

    @LoginRequired
    @PostMapping("list")
    @ApiOperation(value = "发货列表", notes = "支持token和用户id，一个传的时候必须另一个为null")
    public ServerResponse<PageInfo> list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                         String token, Integer userId) throws Exception {
        ServerResponse response = getUserId(token, userId);
        if (response.getStatus() == 0) {
            userId = (Integer) response.getData();
        }else{
            return ServerResponse.createByErrorMessage("请输入正确的用户id");
        }

            return iShippingService.list(userId, pageNum, pageSize);
    }

    /**
     * 查询发货地址列表 louxinlong 无需分页
     *
     * @param token
     * @return
     * @throws Exception
     */
    @LoginRequired
    @PostMapping("selectShippingList")
    @ApiOperation(value = "用户查询发货列表")
    public ServerResponse selectShippingList(String token, Integer userId) throws Exception {

        ServerResponse response = getUserId(token, userId);
        if (response.getStatus() == 0) {
            userId = (Integer) response.getData();
        }else{
            return ServerResponse.createByErrorMessage("请输入正确的用户id");
        }
        return iShippingService.selectShippingList(userId);
    }

    /**
     * 查询默认发货地址 louxinlong
     *
     * @param token
     * @return
     * @throws Exception
     */
    @LoginRequired
    @PostMapping("selectDefaultShipping")
    @ApiOperation(value = "用户查询默认发货列表")
    public ServerResponse<MallShipping> selectDefaultShipping(String token, Integer userId) throws Exception {

        ServerResponse response = getUserId(token, userId);
        if (response.getStatus() == 0) {
            userId = (Integer) response.getData();
        }else{
            return ServerResponse.createByErrorMessage("请输入正确的用户id");
        }
        return iShippingService.selectDefaultShipping(userId);
    }


    //设置默认地址
    @LoginRequired
    @PostMapping("default")
    @ApiOperation(value = "默认地址")
    public ServerResponse<MallShipping> defaultAddress(int shippingId, String token, Integer userId) throws Exception {

        ServerResponse response = getUserId(token, userId);
        if (response.getStatus() == 0) {
            userId = (Integer) response.getData();
        }else{
            return ServerResponse.createByErrorMessage("请输入正确的用户id");
        }
        MallShipping shipping = iShippingService.selectByShippingId(shippingId).getData();
        shipping.setDefaultCheck(1);
        check_only(userId, shipping);

        return iShippingService.update(userId, shipping);
    }

    private ServerResponse check_only(int userId, MallShipping shipping) {

        if (shipping.getDefaultCheck() == null) {
            return ServerResponse.createByStatus(ResponseCode.SHIPPING_CHECK_NOT_FOUND.getCode(), ResponseCode.SHIPPING_CHECK_NOT_FOUND.getDesc(), null);
        }
        //如果该地址为默认地址，则将其他的默认地址去掉
        if (shipping.getDefaultCheck() == 1) {
            List<MallShipping> shipList = iShippingService.list(userId).getData();
            if (shipList != null && shipList.size() > 0) {
                for (MallShipping ship : shipList) {

                    if (ship.getId() == shipping.getId()) {
                        continue;
                    }
                    if (ship.getDefaultCheck() == 1) {
                        ship.setDefaultCheck(0);
                        iShippingService.update(userId, ship);
                    }
                }
            }

        }
        return ServerResponse.createBySuccess("设置成功");

    }

     ServerResponse<Integer> getUserId(String token, Integer userId) throws Exception {
       //普通用户
        if (null == userId || "".equals(userId)) {
            SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
            return ServerResponse.createBySuccess(user.getUserId());
        } else {
            SysUser user = userMapper.selectByUserId(userId);
            if (null == user) return ServerResponse.createByError();
            return ServerResponse.createBySuccess(userId);
        }

    }
}
